package cn.t.listener;

import cn.t.core.exception.BizException;
import cn.t.dto.order.ExcelReconciliationAddDTO;
import cn.t.core.enums.base.CommonError;
import cn.t.utils.ExcelImportValidUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author l
 */
public class ReconciliationImportInfoListener extends AnalysisEventListener<ExcelReconciliationAddDTO> {

    private Integer total;

    @Override
    public void invoke(ExcelReconciliationAddDTO reconciliationAddDTO, AnalysisContext analysisContext) {
        total = analysisContext.readSheetHolder().getApproximateTotalRowNumber() - 1;
        try {
            List<String> valid = ExcelImportValidUtil.valid(reconciliationAddDTO);
            if (!CollectionUtils.isEmpty(valid)) {
                reconciliationAddDTO.setErrorMessages(valid);
            }
        } catch (Exception e) {
            throw new BizException(CommonError.BIZ_EXCEPTION, "excel解析异常");
        }
        reconciliationAddDTO.setRowIndex(analysisContext.readRowHolder().getRowIndex() + 1);
        Field[] fields = reconciliationAddDTO.getClass().getFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object obj = field.get(reconciliationAddDTO);
                if (null != obj) {
                    field.set(reconciliationAddDTO, ((String) obj).trim());
                }
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    public Integer getTotal() {
        return this.total;
    }
}
